package de.matusystems

import grails.converters.JSON;
import groovy.json.JsonSlurper

class NewsletterService {

	def contentProviderService

	def imageTransformationWebService
	def storageWebService
	def emailWebService
	def userWebService

	JsonSlurper slurper = new JsonSlurper()

	def signUp(String firstname, String lastname, String email) {

		Long userId = extractUserId(userWebService.createUser(firstname, lastname, email))

		new SignUp(userId:userId).save(flush:true, failOnError:true)
	}

	private Long extractUserId(JSON json) {
		def result = slurper.parseText(json.toString())
		result['data']['id']
	}

	def generateNewsletter() {

		def content = contentProviderService.getLatestEntries()

		def images = content.collect { it['image'] }

		def thumbnails = []
		images.each { image ->
			thumbnails << imageTransformationWebService.createThumbnail(image, 200, 200)
		}

		def thumbnailUrls = []
		thumbnails.each { thumbnail ->
			thumbnailUrls << extractImageUrl(storageWebService.saveFile("thumbnail", "image/jpeg", thumbnail))
		}

		def newsletterHtml = generateHtml(content, thumbnailUrls)

		new Newsletter(htmlContent:newsletterHtml).save(flush:true, failOnError:true)
	}

	private String extractImageUrl(JSON json) {
		def result = slurper.parseText(json.toString())
		result['link']
	}

	private String generateHtml(List<Map<String, String>> content, List<String> thumbnailUrls) {
		StringBuilder html = new StringBuilder("<html><head></head><title>Newsletter</title><body><table><tbody>")

		for(int i=0; i<content.size(); i++){
			def entry = content.get(i)
			html << "<tr>"

			html << "<td><h2>${entry['title']}</h2><img src=\"${thumbnailUrls.get(i)}\" /></td>"
			html << "<td><p>"+entry['text']+"</p></td>"

			html << "</tr>"
		}

		html << "</tbody></table></body></html>"
	}

	def sendNewsletter() {
		Newsletter latestNewsletter = Newsletter.createCriteria().list{
			eq('sent', false)
			maxResults(1)
			order("id","desc")//assuming auto increment just to make sure
		}[0]

		if(!latestNewsletter){
			println "There is no Newsletter to send."
			return
		}

		println "There is a Newsletter from ${latestNewsletter.dateCreated}"

		List<SignUp> signUps = SignUp.list()

		List<User> users = []
		signUps.each { signUp ->
			users << extractUser(userWebService.getUser(signUp.userId))
		}

		println "Sending mail to ${users.size} useres..."
		users.each { user ->
			println "Sending mail to ${user.email}..."
			emailWebService.sendEmail(user.email, "Newsletter", latestNewsletter.htmlContent)
		}
		println "Sending mail finished."

		latestNewsletter.sent = true
		latestNewsletter.save(flush:true, failOnError:true)

		return ['users':users, 'newsletter':latestNewsletter]
	}

	private User extractUser(JSON json) {
		def result = slurper.parseText(json.toString())
		new User(userId:result['data']['id'], email:result['data']['email'], firstname:result['data']['firstname'], lastname:result['data']['lastname'])
	}
}

class User {
	Long userId
	String email
	String firstname
	String lastname
}
